import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'

export function createPromiseDialog(component, options = {}) {
  return config => {
    return new Promise((resolve, reject) => {
      const div = document.createElement('div')
      document.body.appendChild(div)

      function destroyEle() {
        vm.$destroy()
        vm.$el.remove()
        resolve('弹框关闭')
      }

      const vm = new Vue({
        el: div,
        data() {
          return {
            title: ''
          }
        },
        // 延迟关闭等待关闭动画结束
        watch: {
          visible(newVal) {
            if (!newVal) {
              setTimeout(() => {
                destroyEle()
              }, 300)
            }
          }
        },
        render(h) {
          const self = this
          return h(
            ElementUI.Dialog,
            {
              props: {
                visible: true,
                ...options,
                ...config,
                title: config.title
              },
              on: {
                close: destroyEle
              }
            },
            [
              h(component, {
                on: {
                  ok: args => {
                    resolve(args)
                    destroyEle()
                  },
                  cancel: args => {
                    reject(args)
                    destroyEle()
                  },
                  title: _title => {
                    this.title = _title
                  }
                }
              })
            ]
          )
        }
      })
      vm.$mount(div)
    })
  }
}
